/*************************************************************************
    > File Name: client.cpp
    > Author: Lancer
    > Mail: 18826075768@163.com
************************************************************************/

#include <iostream>
#include <pthread.h>
#include <unistd.h>

using namespace std;

pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;

int x = 10;
int y = 20;

void* func1(void* args){
    cout << "func1 start" << endl;
    pthread_mutex_lock(&qlock);
    while(x < y){
        pthread_cond_wait(&qready, &qlock);
    }
    sleep(1);
    pthread_mutex_unlock(&qlock);
    sleep(3);
    cout << "func1 end" << endl;
}

void* func3(void* args){
    cout << "func3 start" << endl;
    pthread_mutex_lock(&qlock);
    while(x < y){
        pthread_cond_wait(&qready, &qlock);
    }
    pthread_mutex_unlock(&qlock);
    sleep(10);
    cout << "func3 end" << endl;
}

void* func2(void* args){
    cout << "func2 start" << endl;
    pthread_mutex_lock(&qlock);
    x = 20;
    y = 10;
    cout << "has changed x and y" << endl;
    pthread_mutex_unlock(&qlock);
    if(x > y){
        //pthread_cond_signal(&qready);
        pthread_cond_broadcast(&qready);
    }
    // sleep(10);
    // if(x > y){
    //     pthread_cond_signal(&qready);
    // }
    cout << "func2 end" << endl;
}

int main(){
    pthread_t tid1, tid2, tid3;
    int ret;
    ret = pthread_create(&tid1, NULL, func1, NULL);
    if(ret){
        cout << "thread 1 create error" << endl;
        return ret;
    }
    sleep(1);
    ret = pthread_create(&tid3, NULL, func3, NULL);
    if(ret){
        cout << "thread 3 create error" << endl;
        return ret;
    }
    sleep(2);

    ret = pthread_create(&tid2, NULL, func2, NULL);
    if(ret){
        cout << "thread 2 create error" << endl;
        return ret;
    }
    sleep(20);

    return 0;
}